package com.lmk.org.controller;

import com.lmk.basic.util.AjaxResult;
import com.lmk.basic.util.PageList;
import com.lmk.org.domain.Department;
import com.lmk.org.query.DepartmentQuery;
import com.lmk.org.service.DepartmentService;
import com.lmk.system.annotation.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// 由于前后端分离，由于我们只需要返回一个json格式的数据，所以采用该注解
@RestController
// 请求映射地址第一层
@RequestMapping("/department")
public class DepartmentController {
    // 自动注入
    @Autowired
    private DepartmentService service;

    // 查询所有,使用get请求
    @GetMapping
    public List<Department> findAll(){
        List<Department> list = service.findAll();
        return list;
    }
    // 查询单个
    @GetMapping("/{id}")
    // @PathVariable("id")从路径上获取id
    public Department findOne(@PathVariable("id") Long id){
        Department byId = service.findById(id);
        return byId;
    }
    // 分页查询
    @PostMapping
    // @RequestBody 从请求体中获取数据
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
        PageList<Department> list = service.queryPage(query);
        return list;
    }
    // 删除
    @DeleteMapping("/{id}")
    @PreAuthorize(name="部门删除",sn="department:delete")
    public AjaxResult del(@PathVariable("id") Long id){
        try {
            service.del(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败了");
        }
    }
    // 添加和修改
    @PutMapping
    public AjaxResult addorupdate(@RequestBody Department department){
        try {
            if (department.getId()==null){
                service.add(department);
            }else {
                service.update(department);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }

    }

    @PatchMapping
    public AjaxResult batchdel(@RequestBody List<Long> ids){
        try {
            service.batchdel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"批量删除失败");
        }
    }
    @GetMapping("/deptTree")
    public List<Department> findDeptTree(){
       return service.findDeptTree();

    }

}
